<template>
  <div class="medical-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">🏥 健康档案管理</h1>
          <p class="page-subtitle">细心记录，用心守护，为老人健康保驾护航</p>
        </div>
        <div class="stats-card">
          <div class="stat-item">
            <div class="stat-value">{{ elders.length }}</div>
            <div class="stat-label">负责老人</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ totalRecords }}</div>
            <div class="stat-label">健康记录</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ activeElders }}</div>
            <div class="stat-label">在院老人</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选和操作区域 -->
    <div class="filter-section">
      <el-card shadow="hover">
        <div class="filter-content">
          <div class="filter-left">
            <el-form :inline="true">
              <el-form-item label="👵 选择老人">
                <el-select 
                  v-model="elderId" 
                  filterable 
                  placeholder="请选择要查看健康档案的老人"
                  @change="load"
                  style="width: 300px"
                >
                  <el-option 
                    v-for="e in elders" 
                    :key="e.elderId" 
                    :label="`${e.name}（${e.roomNumber || '未分配'}）`" 
                    :value="e.elderId" 
                  />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
          <div class="filter-right">
            <el-button 
              type="primary" 
              @click="openAdd()"
              size="large"
              class="add-btn"
            >
              <el-icon><Plus /></el-icon>
              记录健康信息
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <div class="content-left">
        <el-card class="records-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">📋 健康记录列表</span>
              <el-tag v-if="elderId" type="success">
                共 {{ tableData.length }} 条记录
              </el-tag>
            </div>
          </template>

          <div v-if="!elderId" class="empty-state">
            <el-icon><User /></el-icon>
            <p>请先选择一位老人查看健康档案</p>
          </div>

          <div v-else-if="tableData.length === 0" class="empty-state">
            <el-icon><Document /></el-icon>
            <p>暂无健康记录</p>
            <el-button type="primary" @click="openAdd()" class="mt-3">
              开始记录健康信息
            </el-button>
          </div>

          <div v-else class="records-list">
            <div 
              v-for="record in tableData" 
              :key="record.recordId"
              class="record-item"
            >
              <div class="record-header">
                <div class="record-title">
                  <el-icon><FirstAidKit /></el-icon>
                  <span class="diagnose-text">{{ record.diagnose }}</span>
                </div>
                <div class="record-date">{{ formatDate(record.recordDate) }}</div>
              </div>
              <div class="record-content">
                <div class="treatment-section">
                  <strong>治疗方案：</strong>
                  <span class="treatment-text">{{ record.treatment }}</span>
                </div>
              </div>
              <div class="record-footer">
                <el-tag size="small" type="info">健康记录</el-tag>
                <div class="record-actions">
                  <el-button type="text" size="small" @click="viewDetail(record)">
                    <el-icon><View /></el-icon>
                    查看详情
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <div class="content-right">
        <el-card class="info-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">💡 健康管理提示</span>
            </div>
          </template>
          <div class="tips-content">
            <div class="tip-item">
              <el-icon><InfoFilled /></el-icon>
              <span>定期记录老人健康状况，及时发现问题</span>
            </div>
            <div class="tip-item">
              <el-icon><WarningFilled /></el-icon>
              <span>注意观察老人日常行为变化，预防疾病</span>
            </div>
            <div class="tip-item">
              <el-icon><SuccessFilled /></el-icon>
              <span>详细记录治疗方案，确保用药安全</span>
            </div>
            <div class="tip-item">
              <el-icon><Clock /></el-icon>
              <span>建议每周至少更新一次健康档案</span>
            </div>
          </div>
        </el-card>

        <el-card class="quick-actions-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="card-title">⚡ 快速操作</span>
            </div>
          </template>
          <div class="actions-content">
            <el-button 
              type="primary" 
              @click="openAdd()"
              class="action-btn"
              :disabled="!elderId"
            >
              <el-icon><EditPen /></el-icon>
              新增健康记录
            </el-button>
            <el-button 
              type="success"
              class="action-btn"
              :disabled="!elderId"
            >
              <el-icon><Printer /></el-icon>
              打印健康报告
            </el-button>
            <el-button 
              type="info"
              class="action-btn"
              :disabled="!elderId"
            >
              <el-icon><Download /></el-icon>
              导出健康数据
            </el-button>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog 
      v-model="show" 
      :title="form.recordId ? '编辑健康记录' : '记录健康信息'" 
      width="600px"
    >
      <el-form :model="form" label-width="120px">
        <el-form-item label="👵 选择老人" v-if="!form.recordId">
          <el-select 
            v-model="form.elderId" 
            filterable 
            placeholder="请选择老人"
            style="width: 100%"
          >
            <el-option 
              v-for="e in elders" 
              :key="e.elderId" 
              :label="`${e.name}（${e.roomNumber || '未分配'}）`" 
              :value="e.elderId" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="🏥 诊断结果">
          <el-input 
            type="textarea" 
            v-model="form.diagnose" 
            :rows="3"
            placeholder="请详细描述诊断结果，如：高血压、糖尿病等"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="💊 治疗方案">
          <el-input 
            type="textarea" 
            v-model="form.treatment" 
            :rows="4"
            placeholder="请详细说明治疗方案，包括用药、饮食、运动等建议"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="📅 记录时间">
          <el-date-picker
            v-model="form.recordDate"
            type="datetime"
            placeholder="选择记录时间"
            style="width: 100%"
            :default-value="new Date()"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="show = false" size="large">取消</el-button>
        <el-button type="primary" @click="submit" size="large" :loading="loading">
          保存健康记录
        </el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog 
      v-model="showDetail" 
      title="健康记录详情"
      width="700px"
    >
      <div v-if="currentRecord" class="detail-content">
        <div class="detail-section">
          <h3>👵 老人信息</h3>
          <p>{{ getElderName(currentRecord.elderId) }}</p>
        </div>
        <div class="detail-section">
          <h3>🏥 诊断结果</h3>
          <p>{{ currentRecord.diagnose }}</p>
        </div>
        <div class="detail-section">
          <h3>💊 治疗方案</h3>
          <p>{{ currentRecord.treatment }}</p>
        </div>
        <div class="detail-section">
          <h3>📅 记录时间</h3>
          <p>{{ formatDate(currentRecord.recordDate) }}</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="showDetail = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getMedicalList, addMedical } from '@/api/medical'
import { elderApi } from '@/api/elder'
import { ElMessage } from 'element-plus'
import { 
  Plus, User, Document, FirstAidKit, View, InfoFilled, 
  WarningFilled, SuccessFilled, Clock, EditPen, 
  Printer, Download 
} from '@element-plus/icons-vue'

const elders = ref([])
const elderId = ref(null)
const tableData = ref([])
const show = ref(false)
const showDetail = ref(false)
const loading = ref(false)
const form = ref({})
const currentRecord = ref(null)

// 计算属性
const totalRecords = computed(() => {
  return tableData.value.length
})

const activeElders = computed(() => {
  return elders.value.filter(elder => elder.status !== 'DISCHARGED').length
})

const load = async () => {
  if (!elderId.value) return
  
  try {
    const res = await getMedicalList({ elderId: elderId.value })
    tableData.value = res.data || []
    // 按时间倒序排列
    tableData.value.sort((a, b) => new Date(b.recordDate) - new Date(a.recordDate))
  } catch (error) {
    console.error('加载健康记录失败:', error)
    ElMessage.error('加载健康记录失败')
  }
}

const openAdd = () => {
  form.value = {
    elderId: elderId.value,
    recordDate: new Date()
  }
  show.value = true
}

const submit = async () => {
  if (!form.value.elderId || !form.value.diagnose || !form.value.treatment) {
    ElMessage.warning('请填写完整的健康信息')
    return
  }

  loading.value = true
  try {
    await addMedical(form.value)
    ElMessage.success('健康记录保存成功')
    show.value = false
    load()
  } catch (error) {
    console.error('保存健康记录失败:', error)
    ElMessage.error('保存健康记录失败')
  } finally {
    loading.value = false
  }
}

const viewDetail = (record) => {
  currentRecord.value = record
  showDetail.value = true
}

const getElderName = (elderId) => {
  const elder = elders.value.find(e => e.elderId === elderId)
  return elder?.name || '未知老人'
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

onMounted(async () => {
  try {
    const res = await elderApi.getElders()
    elders.value = res.data || []
  } catch (error) {
    console.error('加载老人列表失败:', error)
    ElMessage.error('加载老人列表失败')
  }
})
</script>

<style scoped>
.medical-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  padding: 30px;
  margin-bottom: 30px;
  color: white;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
}

.title-section .page-title {
  font-size: 2.5rem;
  font-weight: 700;
  margin: 0 0 10px 0;
  background: linear-gradient(45deg, #fff, #e3f2fd);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.title-section .page-subtitle {
  font-size: 1.1rem;
  opacity: 0.9;
  margin: 0;
}

.stats-card {
  display: flex;
  gap: 30px;
  background: rgba(255, 255, 255, 0.2);
  padding: 20px;
  border-radius: 12px;
  backdrop-filter: blur(10px);
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 2rem;
  font-weight: 700;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 0.9rem;
  opacity: 0.8;
}

.filter-section {
  margin-bottom: 30px;
}

.filter-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
}

.filter-left {
  flex: 1;
}

.filter-right {
  flex-shrink: 0;
}

.add-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 10px;
  padding: 12px 24px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.main-content {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 30px;
  max-width: 1400px;
  margin: 0 auto;
}

.content-left, .content-right {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.records-card, .info-card, .quick-actions-card {
  border-radius: 16px;
  border: none;
  transition: all 0.3s ease;
}

.records-card:hover, .info-card:hover, .quick-actions-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 1.3rem;
  font-weight: 600;
  color: #2c3e50;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #bdc3c7;
}

.empty-state .el-icon {
  font-size: 3rem;
  margin-bottom: 15px;
}

.empty-state p {
  margin: 0 0 15px 0;
  font-size: 1rem;
}

.mt-3 {
  margin-top: 15px;
}

.records-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.record-item {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s ease;
  border-left: 4px solid #667eea;
}

.record-item:hover {
  background: #e3f2fd;
  transform: translateX(5px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.record-title {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.record-title .el-icon {
  color: #667eea;
  font-size: 1.2rem;
}

.diagnose-text {
  font-weight: 600;
  color: #2c3e50;
  font-size: 1.1rem;
}

.record-date {
  color: #7f8c8d;
  font-size: 0.9rem;
  flex-shrink: 0;
}

.record-content {
  margin-bottom: 15px;
}

.treatment-section {
  line-height: 1.6;
}

.treatment-section strong {
  color: #34495e;
}

.treatment-text {
  color: #5d6d7e;
}

.record-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-actions .el-button {
  color: #667eea;
}

.tips-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 10px;
  transition: all 0.3s ease;
}

.tip-item:hover {
  background: #e3f2fd;
  transform: translateX(5px);
}

.tip-item .el-icon {
  font-size: 1.2rem;
  color: #667eea;
}

.actions-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.action-btn {
  width: 100%;
  justify-content: flex-start;
  padding: 15px 20px;
  border-radius: 10px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.action-btn:hover {
  transform: translateX(5px);
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-section h3 {
  color: #2c3e50;
  margin-bottom: 8px;
  font-size: 1.1rem;
}

.detail-section p {
  color: #5d6d7e;
  line-height: 1.6;
  margin: 0;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .main-content {
    grid-template-columns: 1fr;
  }
  
  .header-content {
    flex-direction: column;
    text-align: center;
  }
  
  .stats-card {
    justify-content: center;
  }
  
  .filter-content {
    flex-direction: column;
    align-items: stretch;
  }
}

@media (max-width: 768px) {
  .page-header {
    padding: 20px;
  }
  
  .title-section .page-title {
    font-size: 2rem;
  }
  
  .stats-card {
    gap: 20px;
    padding: 15px;
  }
  
  .stat-value {
    font-size: 1.5rem;
  }
  
  .record-header {
    flex-direction: column;
    gap: 8px;
  }
  
  .record-date {
    align-self: flex-start;
  }
}
</style>
